from flask import Flask
import redis
import random
from flask import request


r = redis.Redis(host="10.110.4.54",port=6379,password="1234")

#零时的初始余额
uid = 999
r.set("user_money_" + str(uid),20000)

app = Flask(__name__)
#获取支付码，在用户的手机上
@app.route('/auth_code/get', methods=['GET'])
def auth_code_get():
    uid = 999 #应该是从session
    auth_code = "28" + str(random.randint(1111111111111111, 9999999999999999))
    r.setex("C_" + auth_code,60,str(uid_))
    return auth_code



#支付码支付，商家接口调用
@app.route('/auth_code/pay', methods=['GET'])
def auth_code_pay():
    auth_code = request.args['auth_code']
    fee = int(request.args['fee'])
    key = "C_" + auth_code
    #uid = r.get(key)
    if uid and fee:
        uid = uid.decode("utf-8")
        r.delete(key)

        money_key = "user_money_%s" % uid
        money = r.get(money_key)
        money = int(money.decode("utf-8")) #分为单位
        if money >= fee:
            if r.decrby(money_key, fee) >= 0:
                return '支付成功：%s,%s' % (fee, str(auth_code))
        else:
            return '余额不足：%s' % (money)


    return "扣款失败"

if __name__ == '__main__':
    app.run(debug=False)
	
	